<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>light</title>
  </head>
  <body onload="login()">
    <script src="./socket.io.js"></script>
    <script>
      function postmsg(data) {
        ToFlutter.postMessage(data);
      }
      const url = new URL(location.href);
      // const server='192.168.31.183' //家里
      // const server='192.168.151.96' //手机热点
      // const server='192.168.1.200' //桂林工控机的网卡2地址
      const host = `http://${url.hostname}/`;
      const socket = io(`ws://${url.hostname}:3000`); //测试
      socket.on("updated", (data) => {
        console.log("msg***:");
        console.log(data);
        postmsg(data);
      });

      function login() {
        var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");

        var raw = JSON.stringify({
          CuCode: "001",
          UCode: "admin",
          UPwd: "123",
          imgcode1: "j33a",
        });

        var requestOptions = {
          method: "POST",
          headers: myHeaders,
          body: raw,
          redirect: "follow",
        };

        fetch(host + "Login/DoLogin", requestOptions)
          .then((response) => response.text())
          .then((result) => {
            const waitingOpendoor = localStorage.getItem("waitingOpendoor");
            if (waitingOpendoor) {
              openDoor(waitingOpendoor);
            }
          })
          .catch((error) => console.log("error", error));
      }
      function openDoor(lock) {
        return new Promise((resolve, reject) => {
          localStorage.setItem("waitingOpendoor", "");
          if (typeof lock == "object") {
            lock = JSON.stringify(lock);
          }

          var myHeaders = new Headers();
          myHeaders.append("Content-Type", "application/json");

          var requestOptions = {
            method: "POST",
            headers: myHeaders,
            body: lock,
            redirect: "follow",
          };

          fetch(host + "BoxsSet/OpenlockTest", requestOptions)
            .then((response) => {
              resolve(response.text())
              return response.text()
            })
            .then((result) => {
              if (result.indexOf("登录会话已过期") > -1) {
                localStorage.setItem("waitingOpendoor", lock);
                location.reload(true);
              }
            })
            .catch((error) => {
              reject(error)
              console.log("error", error)
            });
        });
      }
    </script>
  </body>
</html>
